package com.lucy.rabc.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.lucy.common.constant.CommonConst;
import com.lucy.common.domain.ResponseDTO;
import com.lucy.common.redis.RedisCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @author kindear
 * 验证码
 */
@Slf4j
@RestController
@RequestMapping("system")
@Api(tags = "验证码")
public class CaptchaController {
    /** 注入RedisCache 依赖 **/
    @Autowired
    RedisCache redisCache;

    @GetMapping(value = "captcha")
    @ApiOperation(value = "获取图片验证码",notes = "")
    public ResponseDTO<Map<String,String>> getCaptcha(){

        /**
         * 1. 使用 HuTool 工具构建验证码 -- hutool 可以构建多种形式的验证码 ，此处选取较为简单的形式
         * 写入Redis Cache 中验证码信息 --
         */
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(116, 36,4,10);
        log.info("生成的图片验证码:"+lineCaptcha.getCode());
        // 生成和验证码对应的唯一UUID
        String uuid = IdUtil.randomUUID();
        // 将 uuid-code - 生命周期 存入Redis
        redisCache.setCacheObject(CommonConst.CAPTCHA_CODE_KEY.concat(uuid), lineCaptcha.getCode(), CommonConst.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        Map<String,String> captchaMap = new HashMap<>();
        captchaMap.put("uuid",CommonConst.CAPTCHA_CODE_KEY.concat(uuid));
        captchaMap.put("img",lineCaptcha.getImageBase64Data());
        return ResponseDTO.succData(captchaMap);
    }

    @GetMapping("qrcode")
    @ApiOperation(value = "获取二维码",notes = "")
    public ResponseDTO<Object> getQrCode()  {
        // 简单ID
        String uuid = IdUtil.fastSimpleUUID();
        // 配置有效期 5 分钟
        redisCache.setCacheObject(CommonConst.QR_CODE_KEY.concat(uuid), null, 5, TimeUnit.MINUTES);
        // 生成二维码并返回
        QrConfig config = new QrConfig(300, 300);
        String qrCode = QrCodeUtil.generateAsBase64(uuid,config,"png");
        Map<String,String> qrMap = new HashMap<>();
        qrMap.put("uuid",CommonConst.QR_CODE_KEY.concat(uuid));
        qrMap.put("img",qrCode);
        return ResponseDTO.succData(
                qrMap
        );
    }

}
